package com.zmx.common.common.config.shardingsphere;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * @Description: 基于id进行分片 只是拆分颗粒度不同
 * @ClassName: TableByIdShardingAlgorithm
 * @Author zhaomxr
 * @Date 2021-12-13 16:44
 */
@Slf4j
public abstract class TableByIdShardingAlgorithm {

    private final static String SEPARATOR = "_";

    public static String sharding(Collection<String> availableTargetNames, PreciseShardingValue<Integer> preciseShardingValue, int shardingNum) {
        // 真实数据库节点
        availableTargetNames.stream().forEach((item) -> {
            System.out.println("actual db:" + item);
        });

        // 逻辑表以及分片的字段名
        log.info("logicTable:" + preciseShardingValue.getLogicTableName() + ";shardingColumn:" + preciseShardingValue.getColumnName());
        // 分片数据字段值
        log.info("shardingColumn value:" + preciseShardingValue.getValue().toString());

        long memberId = preciseShardingValue.getValue();

        //分片索引计算
        long db_code = memberId & (shardingNum - 1);
        String tb_name = preciseShardingValue.getLogicTableName() + SEPARATOR + db_code;

        // 实际的表名
        log.info("实际的表名 tb_name:" + tb_name);
        for (String each : availableTargetNames) {
            if (each.equals(tb_name)) {
                return each;
            }
        }
        throw new IllegalArgumentException();
    }
}
